import {
	ref
} from 'vue'

const queue = ref([])
const isProcessing = ref(false)
const time = 5000;

// 添加到队列
export const addToQueue = (urls) => {
	queue.value = [...new Set([...queue.value, ...[urls]])];
	processQueue()
}

// 处理队列
const processQueue = async () => {
	if (isProcessing.value || queue.value.length === 0) return
	isProcessing.value = true
	const url = queue.value.shift()
	
	try {
		await cacheImage(url)
		console.log('缓存成功:', url);
	} catch (error) {
		console.error('缓存失败:', url, error);
	} finally {
		setTimeout(() => {
			isProcessing.value = false
			processQueue()
		}, time)
	}
}

// 缓存单张图片
const cacheImage = async (url) => {
	// 1. 下载图片
	const {
		path
	} = await uni.getImageInfo({
		src:url
	});

	// 2. 保存到本地
	const { savedFilePath } = await uni.saveFile({
	  tempFilePath:path,
	})

	// 3. 记录缓存信息
	const cacheInfo = { url, path: savedFilePath, timestamp: Date.now() }
	// uni.setStorageSync(getCacheKey(url), cacheInfo)
	// localStorage.setItem(getCacheKey(url), cacheInfo);

	return savedFilePath
}

// 获取缓存key
const getCacheKey = (url) => `cache_${url.replace(/[^a-z0-9]/gi, '_')}`

// 获取缓存路径
export const getCachedPath = (url) => {
	const cacheInfo = uni.getStorageSync(getCacheKey(url))
	return cacheInfo?.path || null
}

// 清除所有缓存
export const clearAllCache = async () => {
	queue.value = []
	isProcessing.value = false
	// 实际清理逻辑可根据需要添加
}